package com.lxb.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志处理
 */
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.lxb.blog.web.*.*(..))")
    public  void  log(){
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint ){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        //获得方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        //获得方法参数

        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("Request: {} "+requestLog);

    }

    @After("log()")
    public  void doAfter(){
       // logger.info("------------doAfter---------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn( Object result){
        logger.info("Result : {}"+result);

    }

    /**
     * 日志内容
     */
    public class RequestLog{
        private  String url;
        private  String ip;
        private  String calssMethod;
        private  Object[] args;

        public RequestLog(String url, String ip, String calssMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.calssMethod = calssMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "requestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", calssMethod='" + calssMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
